﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Web;
using System.IO;
using MDF.Cacher.Managements;
using MDF.Logger.Managements;
using MDF.Requesting;
using System.Globalization;
using MDF.Utilites.Helper;
using System.Net;
using TGVR.DataHelper.BussinessLogic.BookingSystem;
using TGVR.DataHelper.BussinessObject.BookingSystem;
using TGVR.DataHelper.BussinessObject;

namespace TGVR_Boot
{
    public class VietJetBoot : IBoot
    {
        //string strUsername = "AG38304365";
        //string strPassword = "Pass8317";

        //1: nguoi lon, 2: tre em, 3: tre so sinh
        Requester m_request = new Requester();
        string viewstate = "";
        string debugid = "";

        public static string CookieString = "";

        public string GetError()
        {
            return m_error;
        }

        public List<BK_Ticket> Search(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
          int _iAdut, int _iChild, int _iBaby, bool _isInter, int _iUserID)
        {

            string strKeyword = "VietJetBoot_Search_" + _strStationForm + "_" + _strStationTo + _dtDateFrom.ToString("_MM_dd_yyyy") +
                (_dtDateTo.HasValue ? _dtDateTo.Value.ToString("_MM_dd_yyyy") : "") + _iAdut.ToString() + _iChild.ToString() + _iBaby.ToString() + "_User" + _iUserID;
            //m_log.Info("Search: " + strKeyword);
            var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            if (cacheResult != null)
            {
                //m_log.Info("Get from cache");
                return (List<BK_Ticket>)cacheResult;
            }
            List<BK_Ticket> lstResult = new List<BK_Ticket>();
            if (!this.Login())
            {
                return lstResult;
            }
            Requester rq = m_request;



            string strReturnDay = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("dd") : "";
            string strReturnMonth = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("MM") : "0";
            string strReturnYear = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("yyyy") : "0";
            string strRound = _dtDateTo.HasValue ? "on" : "";

            string strTemp = string.Format("chkRoundTrip={11}&lstOrigAP={0}&lstDestAP={1}&dlstDepDate_Day={2}&dlstDepDate_Month={3}%2F{4}&dlstRetDate_Day={5}&dlstRetDate_Month={6}%2F{7}&lstCurrency=VND&lstResCurrency=VND&lstDepDateRange=0&lstRetDateRange=0&txtNumAdults={8}&txtNumChildren={9}&txtNumInfants={10}&lstLvlService=1&blnFares=False&txtPromoCode=",
                _strStationForm,
                _strStationTo,
                _dtDateFrom.ToString("dd"),
                _dtDateFrom.ToString("yyyy"),
                _dtDateFrom.ToString("MM"),
                strReturnDay,
                strReturnYear,
                strReturnMonth,
                _iAdut,
                _iChild,
                _iBaby,
                strRound
                );

            var respone = rq.PostData("https://ameliaweb5.intelisys.ca/VietJet/ameliapost.aspx?lang=vi", strTemp);
            string htmlRespone = rq.GetHtmlFromResponse(respone);

            strTemp = string.Format("__VIEWSTATE=%2FwEPDwULLTE1MzQ1MjI3MzAPZBYCZg9kFg4CCA8QZGQWAGQCCQ8QZGQWAGQCCw8QZGQWAGQCDQ8QZGQWAGQCEQ8QZGQWAGQCEg8QZGQWAGQCEw8QZGQWAGRkDuhQN17CT5ZIydlFFSt%2BWc8NsCA%3D&SesID=&DebugID=76&lstOrigAP=-1&lstDestAP=-1&dlstDepDate_Day={0}&dlstDepDate_Month={1}%2F1{2}&lstDepDateRange=0&dlstRetDate_Day={3}&dlstRetDate_Month={4}%2F{5}&lstRetDateRange=0&txtNumAdults={6}&txtNumChildren={7}&txtNumInfants={8}&lstLvlService=1&lstResCurrency=VND&lstCurrency=VND&txtPromoCode=",
                _dtDateFrom.ToString("dd"),
                _dtDateFrom.ToString("yyyy"),
                _dtDateFrom.ToString("MM"),
                strReturnDay,
                strReturnYear,
                strReturnMonth,
                _iAdut,
                _iChild,
                _iBaby
                );

            respone = rq.PostData("https://ameliaweb5.intelisys.ca/VietJet/ameliapost.aspx?lang=vi", strTemp);
            htmlRespone = rq.GetHtmlFromResponse(respone);

            lstResult = GetFromHTML(htmlRespone, _strStationForm, _strStationTo, _dtDateFrom, _dtDateTo, _isInter, _iAdut + _iChild, _iUserID);

            if (lstResult != null && lstResult.Count > 0)
            {
                CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
            }

            return lstResult;
        }
        public List<BK_Ticket> SearchCheapest(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? dtDateTo,
            int _iAdut, int _iChild, int _iBaby, int _iUserID)
        {
            if (_dtDateFrom < DateTime.Now)
                _dtDateFrom = DateTime.Now;
            if (dtDateTo.HasValue && dtDateTo < DateTime.Now)
                dtDateTo = DateTime.Now;
            string strKeyword = "VietJetBootSearchCheapest_" + _strStationForm + _strStationTo + _dtDateFrom.ToString("MM_yyyy") +
               (dtDateTo.HasValue ? dtDateTo.Value.ToString("_MM_yyyy_") : "") + _iAdut.ToString() + _iChild.ToString() + _iBaby.ToString() + "_User" + _iUserID;
            //m_log.Info("Search: " + strKeyword);
            //var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            //CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
            if (cacheResult != null)
            {
                return (List<BK_Ticket>)cacheResult;
            }
            //string htmlResult;
            string htmlResult = "";// File.ReadAllText(@"C:\PROJECTS\TheGioiVeRe\Documents\Searching\Cheapest\vj.html");
            if (htmlResult == "")
            {
                Requester rq = new Requester();

                string strReturnDay = dtDateTo.HasValue ? dtDateTo.Value.ToString("dd") : "";
                string strReturnMonth = dtDateTo.HasValue ? dtDateTo.Value.ToString("MM") : "0";
                string strReturnYear = dtDateTo.HasValue ? dtDateTo.Value.ToString("yyyy") : "0";
                string strRound = dtDateTo.HasValue ? "on" : "";

                string strTemp = string.Format("chkRoundTrip={11}&lstOrigAP={0}&lstDestAP={1}&dlstDepDate_Day={2}&dlstDepDate_Month={3}%2F{4}&dlstRetDate_Day={5}&dlstRetDate_Month={6}%2F{7}&lstCurrency=VND&lstResCurrency=VND&lstDepDateRange=0&lstRetDateRange=0&txtNumAdults={8}&txtNumChildren={9}&txtNumInfants={10}&lstLvlService=1&blnFares=True&txtPromoCode=",
                    _strStationForm,
                    _strStationTo,
                    _dtDateFrom.ToString("dd"),
                    _dtDateFrom.ToString("yyyy"),
                    _dtDateFrom.ToString("MM"),
                    strReturnDay,
                    strReturnYear,
                    strReturnMonth,
                    _iAdut,
                    _iChild,
                    _iBaby,
                    strRound
                    );

                var respone = rq.PostData("https://ameliaweb5.intelisys.ca/VietJet/ameliapost.aspx?lang=vi", strTemp);
                string htmlRespone = rq.GetHtmlFromResponse(respone);
                strTemp = string.Format("__VIEWSTATE=%2FwEPDwULLTE1MzQ1MjI3MzAPZBYCZg9kFg4CCA8QZGQWAGQCCQ8QZGQWAGQCCw8QZGQWAGQCDQ8QZGQWAGQCEQ8QZGQWAGQCEg8QZGQWAGQCEw8QZGQWAGRkDuhQN17CT5ZIydlFFSt%2BWc8NsCA%3D&SesID=&DebugID=76&lstOrigAP=-1&lstDestAP=-1&dlstDepDate_Day={0}&dlstDepDate_Month={1}%2F1{2}&lstDepDateRange=0&dlstRetDate_Day={3}&dlstRetDate_Month={4}%2F{5}&lstRetDateRange=0&txtNumAdults={6}&txtNumChildren={7}&txtNumInfants={8}&lstLvlService=1&lstResCurrency=VND&lstCurrency=VND&txtPromoCode=",
                    _dtDateFrom.ToString("dd"),
                    _dtDateFrom.ToString("yyyy"),
                    _dtDateFrom.ToString("MM"),
                    strReturnDay,
                    strReturnYear,
                    strReturnMonth,
                    _iAdut,
                    _iChild,
                    _iBaby
                    );

                respone = rq.PostData("https://ameliaweb5.intelisys.ca/VietJet/ameliapost.aspx?lang=vi", strTemp);
                htmlResult = rq.GetHtmlFromResponse(respone);
            }

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlResult);
            var travels = doc.DocumentNode.SelectNodes("//*[@class=\"hdrTable700\"]");
            if (travels == null)
            {
                LogManager.GetInstance().Warn("VietJet: Không tìm thấy vé");
            }
            if (dtDateTo.HasValue && travels.Count != 2)
                throw new Exception("Không tìm dc lượt về");
            List<BK_Ticket> lstResult = new List<BK_Ticket>();
            var iFee = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, "FeeVietJet").Value);
            //var objFirm  = new FirmDAO().GetByShortName("VJ");
            for (int i = 0; i < travels.Count; i++)
            {
                HtmlDocument doctds = new HtmlDocument();
                doctds.LoadHtml(travels[i].InnerHtml);
                var tickets = doctds.DocumentNode.SelectNodes("//td");
                if (tickets != null)
                    foreach (var ticket in tickets)
                    {
                        if (ticket.Attributes["id"] == null)
                            continue;
                        BK_Ticket t = new BK_Ticket();
                        t.AirType = "vietjet";
                        string strTemp = "ctrValueViewerDep";
                        string strDate = ticket.Attributes["id"].Value.Substring(strTemp.Length);
                        t.StartDate = DateTime.ParseExact(strDate, "yyyyMMdd", CultureInfo.InvariantCulture);
                        t.EndDate = t.StartDate;

                        string strPrice = ticket.InnerHtml.Replace(",", "");
                        strTemp = "<p class=\"vvFare\">";
                        int iStart = strPrice.IndexOf(strTemp) + strTemp.Length;
                        int iEnd = strPrice.IndexOf("</p");
                        strPrice = strPrice.Substring(iStart, iEnd - iStart);
                        t.PriceBefore = Int32.Parse(strPrice);
                        t.Price = (int)(1.1 * (float)t.PriceBefore);
                        t.Price += 93000 + iFee;
                        t.FlightNo = "VJ";
                        t.FromCity = _strStationForm;
                        t.ToCity = _strStationTo;
                        t.Image = "http://thegioivere.net/content/images/logo/VJ.png";
                        lstResult.Add(t);
                        t.TypeWay = i == 0 ? "Out" : "In";



                    }
            }
            if (lstResult != null)
            {
                //CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
                CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
            }
            return lstResult;
        }
        public List<BK_Ticket> GetFromHTML(string htmlRespone, string _strStationForm, string _strStationTo,
            DateTime _dtDateFrom, DateTime? _dtDateTo, bool _isInter, int iTotalPassenger, 
            int _iUserID)
        {
            if (!string.IsNullOrEmpty(htmlRespone))
            {
                List<BK_Ticket> lstResult = new List<BK_Ticket>();
                //if (resResult != null)
                {
                    //string htmlResult = rq.GetHtmlFromResponse(resResult);
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(htmlRespone);
                    //kiểm tra xem đúng chuyến bay không?
                    string strFlights = "";
                    try
                    {
                        strFlights = doc.DocumentNode.SelectNodes("//*[@class=\"bg1\"]")[0].InnerText;
                    }
                    catch
                    {
                        return lstResult;
                    }
                    if (strFlights == null)
                    {
                        return lstResult;
                    }
                    if (htmlRespone.IndexOf(_strStationForm) == -1 || htmlRespone.IndexOf(_strStationTo) == -1)
                    {
                        throw new Exception(string.Format("Vietjet: The result of flight not right! {0}-{1}", _strStationForm, _strStationTo));
                    }

                    //kiểm tra tìm vé không thành công
                    var travles = doc.DocumentNode.SelectNodes("//*[@class=\"FlightsGrid\"]");
                    if (travles == null)
                    {
                        return lstResult;
                    }
                    string strFee = "FeeVietJet";
                    if (_isInter)
                        strFee = "FeeVietJetInter";
                    var iFee = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, strFee).Value);
                    var VJ_Tax_Promo = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, "VJ_Tax_Promo").Value);
                    //VJ_Tax_Promo
                    var vnFirm = TK_FirmBUS.Current.GetFirmByShortName("VJ");
                    if (travles != null && travles.Count > 0)
                    {
                        //từng lượt
                        int i = 0;
                        foreach (var travel in travles)
                        {
                            //lấy ngày trên hãng
                            //
                            string strDate = doc.DocumentNode.SelectNodes("//*[@id=\"travOpsMain\"]//table//tr[3]//td[1]//b")[i].InnerText.Split(' ')[0];
                            DateTime dtTemp = DateTime.ParseExact(strDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

                            if (i == 0 && dtTemp.ToString("ddMMyyyy") != _dtDateFrom.ToString("ddMMyyyy"))
                            {
                                throw new Exception("Tìm vé đi sai ngày");
                            }
                            if (i == 1 && dtTemp.ToString("ddMMyyyy") != _dtDateTo.Value.ToString("ddMMyyyy"))
                            {
                                throw new Exception("Tìm vé về sai ngày");
                            }
                            //lấy xong ngày

                            HtmlDocument docDepart = new HtmlDocument();
                            docDepart.LoadHtml(travel.InnerHtml);
                            var tickets = docDepart.DocumentNode.SelectNodes("//tr[contains(@id,'gridTravelOptDep')]");//gridTravelOptRet

                            if (i == 1)
                            {
                                tickets = docDepart.DocumentNode.SelectNodes("//tr[contains(@id,'gridTravelOptRet')]");//gridTravelOptRet
                            }
                            if (tickets == null)
                                continue;
                            //từng vé
                            for (int j = 0; j < tickets.Count; j++)// ; ticket in tickets)
                            {
                                //var ticket = tickets[j]; 
                                HtmlDocument docTicket = new HtmlDocument();
                                docTicket.LoadHtml(tickets[j].InnerHtml);
                                var tds = docTicket.DocumentNode.SelectNodes("//td[@class=\"SegInfo\"]");//gridTravelOptRet



                                BK_Ticket t = new BK_Ticket();
                                t.Profit = iFee;
                                t.ChildPricePercent = vnFirm.Child;
                                t.BabyPricePercent = vnFirm.Baby;
                                t.IsInter = _isInter;
                                t.AirType = "vietjet";
                                string strTemp = tds[1].InnerText.Trim();

                                t.EndDate = DateTime.ParseExact(_dtDateFrom.ToString("MM/dd/yyyy") + " " + strTemp.Substring(0, strTemp.IndexOf("&nbsp;")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);

                                strTemp = tds[2].InnerHtml.Trim();

                                t.FlightNo = strTemp.Substring(0, strTemp.IndexOf("<br"));
                                if (i == 0)
                                {
                                    t.FromCity = _strStationForm;
                                    t.ToCity = _strStationTo;
                                }
                                else
                                {
                                    t.ToCity = _strStationForm;
                                    t.FromCity = _strStationTo;
                                }
                                t.LastUpdate = DateTime.Now;



                                var prices = docTicket.DocumentNode.SelectNodes("//input[@type=\"radio\"]");//gridTravelOptRet
                                if (prices == null)
                                    continue;
                                //1,E_Promo,O
                                t.DataToBook = prices[0].Attributes["value"].Value;

                                //t.PriceBefore = Int32.Parse(prices[0].ParentNode.InnerText.Trim().Replace(",", ""));

                                var total_complete_charges = docTicket.DocumentNode.SelectNodes("//input[@id=\"total_complete_charges\"]")[0].Attributes["value"].Value.Replace(",", "");
                                t.PriceBefore = Int32.Parse(total_complete_charges) / iTotalPassenger;
                                t.Price = t.PriceBefore + iFee;
                                /* Gia cu
                                if (_isInter)
                                {
                                    //id="charges"
                                    t.Price = t.PriceBefore;
                                    var strFeeOnWeb = docTicket.DocumentNode.SelectNodes("//input[@id=\"charges\"]")[0].Attributes["value"].Value.Replace(",", "");
                                    int iFeeOnWeb = Int32.Parse(strFeeOnWeb);
                                    //if (_dtDateTo.HasValue)
                                    iFeeOnWeb = iFeeOnWeb / iTotalPassenger;
                                    t.Price += iFeeOnWeb + iFee;
                                }
                                else
                                {
                                    t.Price = (int)(1.1 * (float)t.PriceBefore);
                                    t.Price += 93000 + iFee;

                                }
                                 * */
                                if (t.FromCity == _strStationForm)
                                {
                                    t.TypeWay = "Out";
                                    strTemp = tds[0].InnerText.Trim();

                                    if (strTemp.IndexOf("&nbsp;") > -1)
                                    {
                                        t.StartDate = DateTime.ParseExact(_dtDateFrom.ToString("MM/dd/yyyy") + " " + strTemp.Substring(0, strTemp.IndexOf("&nbsp;")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                        string strTemp1 = tds[1].InnerText.Trim();

                                        t.EndDate = DateTime.ParseExact(_dtDateFrom.ToString("MM/dd/yyyy") + " " + strTemp1.Substring(0, strTemp.IndexOf("&nbsp;")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                    }
                                    else
                                        if (strTemp.IndexOf(' ') > -1)
                                        {
                                            t.StartDate = DateTime.ParseExact(_dtDateFrom.ToString("MM/dd/yyyy") + " " + strTemp.Substring(0, strTemp.IndexOf(" ")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                            string strTemp1 = tds[1].InnerText.Trim();

                                            t.EndDate = DateTime.ParseExact(_dtDateFrom.ToString("MM/dd/yyyy") + " " + strTemp1.Substring(0, strTemp.IndexOf(" ")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                        }
                                }

                                if (_dtDateTo.HasValue && t.FromCity == _strStationTo)
                                {
                                    t.TypeWay = "In";
                                    strTemp = tds[0].InnerText.Trim();
                                    if (strTemp.IndexOf("&nbsp;") > -1)
                                    {
                                        t.StartDate = DateTime.ParseExact(_dtDateTo.Value.ToString("MM/dd/yyyy") + " " + strTemp.Substring(0, strTemp.IndexOf("&nbsp;")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                        string strTemp1 = tds[1].InnerText.Trim();

                                        t.EndDate = DateTime.ParseExact(_dtDateTo.Value.ToString("MM/dd/yyyy") + " " + strTemp1.Substring(0, strTemp.IndexOf("&nbsp;")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                    }
                                    else
                                    {
                                        if (strTemp.IndexOf(' ') > -1)
                                            t.StartDate = DateTime.ParseExact(_dtDateTo.Value.ToString("MM/dd/yyyy") + " " + strTemp.Substring(0, strTemp.IndexOf(" ")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                        string strTemp1 = tds[1].InnerText.Trim();

                                        t.EndDate = DateTime.ParseExact(_dtDateTo.Value.ToString("MM/dd/yyyy") + " " + strTemp1.Substring(0, strTemp.IndexOf(" ")), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                    }
                                    t.ReturnDate = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("dd/MM/yyyy") : "";
                                }
                                t.Image = "http://thegioivere.net/content/images/logo/VJ.png";

                                //Holding time
                                //>24h
                                t.HoldToDate = DateTime.Now;
                                if (DateTime.Now < t.StartDate.AddHours(-24))
                                    t.HoldToDate = DateTime.Now.AddHours(24);
                                //<24, >12
                                if ((DateTime.Now >= t.StartDate.AddHours(-24)) && (DateTime.Now < t.StartDate.AddHours(-12)))
                                    t.HoldToDate = t.StartDate.AddHours(-12);
                                //<12h
                                if ((DateTime.Now > t.StartDate.AddHours(-12)))
                                    t.HoldToDate = DateTime.Now.AddHours(0.5);
                                if (t.DataToBook.IndexOf("Promo") > -1)
                                {
                                    t.IsPromo = true;
                                    t.Price += VJ_Tax_Promo;
                                    t.PriceBefore += VJ_Tax_Promo;
                                }
                                lstResult.Add(t);
                            }
                            i++;
                        }
                    }
                    return lstResult;
                }
            }
            return null;
        }
        void XuLy(string html)
        {
            try
            {
                HtmlDocument docDepart = new HtmlDocument();
                docDepart.LoadHtml(html);
                var nodesviewstate = docDepart.DocumentNode.SelectNodes("//*[@id=\"__VIEWSTATE\"]");
                var notedebugid = docDepart.DocumentNode.SelectNodes("//*[@id=\"DebugID\"]");
                viewstate = HttpUtility.UrlEncode(nodesviewstate[0].Attributes["value"].Value);
                debugid = notedebugid[0].Attributes["value"].Value;
            }
            catch
            { }
        }
        public string resnumber = "";
        public string thanhtien = "";
        private string m_error;
        private System.Net.WebResponse respones;
        public Dictionary<string, string> lstResultHTML = new Dictionary<string, string>();
        /// <summary>
        /// Lấy mã vé
        /// </summary>
        /// <returns></returns>
        public string GetCode()
        {
            return resnumber;
        }
        private DateTime HoldToDate = DateTime.Now;
        public DateTime GetHoldToDate()
        {
            return HoldToDate;
        }
        /// <summary>
        /// Lấy tổng tiền
        /// </summary>
        /// <returns></returns>
        public int GetTotal()
        {
            try
            {
                if (!string.IsNullOrEmpty(thanhtien))
                    return Int32.Parse(thanhtien.Replace(".", ""));
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("VJ: Cant get total price!", ex);
            }

            return 0;
        }
        void GetResNumber(string html)
        {
            HtmlDocument docDepart = new HtmlDocument();
            docDepart.LoadHtml(html);
            try
            {
                var nodesresnumber = docDepart.DocumentNode.SelectNodes("//*[@class=\"ResNumber\"]");
                resnumber = nodesresnumber[0].InnerText;
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Vietjet: Can not get code", ex);
            }
            //var nodestotalmoney = docDepart.DocumentNode.SelectNodes("//*[@class=\"ChargesTotal\"]//td[2]");
            try
            {
                thanhtien = docDepart.DocumentNode.SelectNodes("//*[@class=\"ChargesTotal\"]//td[2]")[0].InnerText.Replace(",", "");
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Vietjet: Can not get gross price ", ex);
            }
            try
            {
                //HoldToDate ////*[@id="Itinerary"]/h1[2]
                // 0    1     2     3    4        5      6    7      8
                //Nếu không thanh toán, đến  12/06/2014 Thu 17:50 (GMT+7), đặt chỗ của bạn sẽ tự động bị hủy.
                var tempHoldToDate = docDepart.DocumentNode.SelectNodes("//h1")[2].InnerText.Split(' ');
                string strTime = tempHoldToDate[6] + " " + tempHoldToDate[8];
                HoldToDate = DateTime.ParseExact(strTime, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Vietjet: Can not get HoldToDate", ex);
            }
        }
        public bool Login()
        {
            try
            {
                //#region Check logged in
                //Requester stRequest = m_request;
                //string strHomeLink = "https://ameliaweb3.intelisys.ca/VietJet/AgentOptions.aspx?lang=vi&st=sl&sesid=";
                //var reps = stRequest.GetData(strHomeLink);
                //var html = stRequest.GetHtmlFromResponse(reps);
                //if (html.IndexOf("Menu Lựa chọn") > -1)
                //{
                //    LogManager.GetInstance().Warn("Vietjet: Logged In");
                //    return true;
                //}
                //#endregion
                #region Login
                Requester stRequest = m_request;
                string login = "https://ameliaweb3.intelisys.ca/VietJet/sitelogin.aspx?lang=vi";
                var reps = stRequest.GetData(login);
                var html = stRequest.GetHtmlFromResponse(reps);
                string viewstate = "", debugid = "";
                string strUsername = "AG38317205";
                string strPassword = "Pass8318";
                try
                {
                    HtmlDocument docDepart = new HtmlDocument();
                    docDepart.LoadHtml(html);
                    var nodesviewstate = docDepart.DocumentNode.SelectNodes("//*[@id=\"__VIEWSTATE\"]");
                    var notedebugid = docDepart.DocumentNode.SelectNodes("//*[@id=\"DebugID\"]");
                    viewstate = HttpUtility.UrlEncode(nodesviewstate[0].Attributes["value"].Value);
                    debugid = notedebugid[0].Attributes["value"].Value;
                }
                catch
                { }
                string strLinkLogin = "https://ameliaweb3.intelisys.ca/VietJet/sitelogin.aspx?lang=vi";
                string strData = "__VIEWSTATE=" + viewstate + "&SesID=&DebugID=" + debugid + "&txtAgentID=" + strUsername + "&txtAgentPswd=" + strPassword;
                var respones = stRequest.PostData(strLinkLogin, strData);
                html = stRequest.GetHtmlFromResponse(respones);
                if (html.IndexOf("Menu Lựa chọn") == -1 && html.IndexOf("Logged In") == -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Can not login");
                    return false;
                }
                LogManager.GetInstance().Info("Vietjet: Log in successfull!");
                //m_request.Cookie
                return true;
                #endregion
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Vietjet: Login error!", ex);
                return false;
            }
        }
        private void SaveHTML(BK_Booking booking, Dictionary<string, string> lstResultHTML)
        {
            int index = 1;
            foreach (var item in lstResultHTML)
            {
                FileHelper.WriteFile(item.Value, "BookingLogFiles", "ERROR_VIETJET_" + DateTime.Now.ToString("dd_MM_HH_mm_") + booking.Phone + "_" + index + item.Key + ".html");
                index++;
            }
        }
        public int MakeBooking(BK_Booking booking, BK_Passenger[] passenges, BK_Ticket tkDepart, BK_Ticket tkReturn, int _iUserID)
        {
            try
            {
                if (!this.Login())
                {
                    return (int)BookingStatus.NOTLOGIN;
                }
                string strEmailDefault = "thegioivere@gmail.com";

                bool isBackReturnToDepart = false;
                if (tkDepart == null && tkReturn != null)//2 chieu # hang
                {
                    isBackReturnToDepart = true;
                    tkDepart = tkReturn;
                    tkReturn = null;
                }

                int iDayTimeOut = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, "TimeoutBookVietJet").Value);

                if (tkDepart.StartDate.AddHours(iDayTimeOut) <= DateTime.Now)
                {
                    m_error = "Quá hạn book vé";
                    return (int)BookingStatus.OUTOFBOOKING;
                }

                #region 2.Lấy trang chủ
                string strHomeLink = "https://ameliaweb3.intelisys.ca/VietJet/AgentOptions.aspx?lang=vi&st=sl&sesid=";
                var reps = m_request.GetData(strHomeLink);
                var html = m_request.GetHtmlFromResponse(reps);
                XuLy(html);

                //#region Try Login

                //if (html.IndexOf("Menu Lựa chọn") == -1)
                //{
                //    _CookieCC = null;
                //    Login();
                //    m_request.CookieCC = _CookieCC;
                //    reps = m_request.GetData(strHomeLink);
                //    html = m_request.GetHtmlFromResponse(reps);
                //    XuLy(html);
                //}

                //#endregion

                lstResultHTML[strHomeLink] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                XuLy(html);

                string add2 = "https://ameliaweb3.intelisys.ca/VietJet/AgentOptions.aspx?lang=vi&st=sl&sesid=";
                string data2 = "__VIEWSTATE=" + viewstate + "&SesID=&DebugID=" + debugid + "&button=bookflight";
                respones = m_request.PostData(add2, data2);
                //reps = m_request.GetData(respones.ResponseUri.ToString());
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add2] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                XuLy(html);
                //viewstate : "%2fwEPDwULLTIxMTUyMDY4MzgPZBYCZg9kFhACBg8QZGQWAGQCBw8QZGQWAGQCCg8QZGQWAGQCCw8QZGQWAGQCDA8QZGQWAGQCDQ8QZGQWAGQCDg8QZGQWAGQCEw8QZGQWAGRktuiPQXd4JyfvJTzBeZEMvuOycAw%3d"
                #endregion

                #region 3.Tìm vé

                string strReturnDay = tkReturn != null ? tkReturn.StartDate.ToString("dd") : "";
                string strReturnMonth = tkReturn != null ? tkReturn.StartDate.ToString("MM") : "0";
                string strReturnYear = tkReturn != null ? tkReturn.StartDate.ToString("yyyy") : "0";
                string strRound = tkReturn != null ? "on" : "";

                //1: nguoi lon, 2: tre em, 3: tre so sinh
                int iAdut = passenges.Count(m => m.TypeID == 1);
                int iChild = passenges.Count(m => m.TypeID == 2);
                int iBaby = passenges.Count(m => m.TypeID == 3);

                string add3 = "https://ameliaweb3.intelisys.ca/VietJet/ViewFlights.aspx?lang=vi&st=sl&sesid=";
                string data3 = string.Format("__VIEWSTATE={0}&SesID=&DebugID={1}&button=vfto&dlstDepDate_Day={2}&dlstDepDate_Month={3}%2F{4}&dlstRetDate_Day={5}&dlstRetDate_Month={6}%2F{7}&lstDepDateRange=0&lstRetDateRange=0&SesID=&DebugID={1}&chkRoundTrip={8}&lstOrigAP={9}&lstDestAP={10}&departure1=4%2F1%2F2014&departTime1=0000&departure2=25%2F01%2F2014&departTime2=0000&lstLvlService=1&lstResCurrency=VND&txtNumAdults={11}&txtNumChildren={12}&txtNumInfants={13}&lstCompanyList=1383%C6%92CTY+TNHH+THE+GIOI+VE+RE&txtPONumber=",
                    viewstate,//0
                    debugid,//1
                    tkDepart.StartDate.ToString("dd"),//2
                    tkDepart.StartDate.ToString("yyyy"),//3
                    tkDepart.StartDate.ToString("MM"),//4
                    strReturnDay,//5
                    strReturnYear,//6
                    strReturnMonth,//7
                    strRound,//8
                    booking.FromCity,//9
                    booking.ToCity,//10
                    iAdut,//11
                    iChild,//12
                    iBaby//13
                    );

                respones = m_request.PostData(add3, data3);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add3] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                XuLy(html);

                List<BK_Ticket> lstTickets = null;
                string strKeyword = "VietJetBoot_Search_" + booking.FromCity + "_" + booking.ToCity + tkDepart.StartDate.ToString("_MM_dd_yyyy") +
                    (tkReturn != null ? tkReturn.StartDate.ToString("_MM_dd_yyyy") : "");
                if (tkReturn != null)
                {
                    lstTickets = GetFromHTML(html, booking.FromCity, booking.ToCity, tkDepart.StartDate, tkReturn.StartDate, tkDepart.IsInter, passenges.Where(m => m.TypeID != 3).Count(), _iUserID);
                }
                else
                {
                    lstTickets = GetFromHTML(html, booking.FromCity, booking.ToCity, tkDepart.StartDate, null, tkDepart.IsInter, passenges.Where(m => m.TypeID != 3).Count(), _iUserID);
                }

                int indexvedi = -1, indexveve = -1;
                for (int i = 0; i < lstTickets.Count; i++)
                {
                    if (lstTickets[i].FlightNo.Replace(" ", "").ToLower() == tkDepart.FlightNo.Replace(" ", "").ToLower() && lstTickets[i].TypeWay == "Out" && lstTickets[i].StartDate.ToString("ddMMyyyyHHmm") == tkDepart.StartDate.ToString("ddMMyyyyHHmm"))
                    {
                        indexvedi = i;
                    }
                    else
                        if (tkReturn != null && lstTickets[i].FlightNo.Replace(" ", "").ToLower() == tkReturn.FlightNo.Replace(" ", "").ToLower() && lstTickets[i].TypeWay == "In" && lstTickets[i].StartDate.ToString("ddMMyyyyHHmm") == tkReturn.StartDate.ToString("ddMMyyyyHHmm"))
                        {
                            indexveve = i;
                        }
                }

                if (lstTickets == null || lstTickets.Count == 0)
                {
                    LogManager.GetInstance().Warn("Vietjet: No search search");

                    return (int)BookingStatus.NORESULTFIND;
                }

                if (indexvedi == -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Not match depart ticket");

                    return (int)BookingStatus.NOTMACTHDEPART;
                }

                if (tkReturn != null && indexveve == -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Not match return ticket");

                    return (int)BookingStatus.NOTMACTHRETURN;
                }

                if (lstTickets[indexvedi].Price != tkDepart.Price)
                //throw new Exception("Có sự thay đổi giá vé lượt đi. Vui lòng tìm lại vé");
                {
                    LogManager.GetInstance().Warn("Vietjet: " + BookingStatus.CHANGEDPRICE);




                    return (int)BookingStatus.CHANGEDPRICE;
                }
                if (tkReturn != null && lstTickets[indexveve].Price != tkReturn.Price)
                //throw new Exception("Có sự thay đổi giá vé lượt về. Vui lòng tìm lại vé");
                {
                    LogManager.GetInstance().Warn("Vietjet: " + BookingStatus.CHANGEDPRICE);



                    return (int)BookingStatus.CHANGEDPRICE;
                }
                #endregion

                #region 4.Chọn vé

                //viewstate : "%2fwEPDwUKLTE5MTEzMzQ2M2RkiJ5fET0NpZMbwSDKY5uQTQHXRSA%3d"
                //buoc 4
                string add4 = "https://ameliaweb3.intelisys.ca/VietJet/TravelOptions.aspx?lang=vi&sesid=";
                string data4 = string.Format("__VIEWSTATE=" + viewstate + "&button=continue&SesID=&DebugID=" + debugid + "&PN=&gridTravelOptDep={0}&gridTravelOptRet={1}",
                    indexvedi != -1 ? HttpUtility.UrlEncode(lstTickets[indexvedi].DataToBook) : "",
                    indexveve != -1 ? HttpUtility.UrlEncode(lstTickets[indexveve].DataToBook) : ""
                    );
                respones = m_request.PostData(add4, data4);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add4] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                XuLy(html);
                CacheManager.GetInstance().Delete(strKeyword);
                #endregion

                #region 5.Điền thông tin hành khách
                //buoc 5
                string add5 = "https://ameliaweb3.intelisys.ca/VIETJET/Details.aspx?lang=vi&sesid=";
                string data5 = "__VIEWSTATE=" + viewstate + "&SesID=&DebugID=" + debugid + "&button=continue&txtResNotes=";

                //Điền thông tin cho người lớn
                var lstAduts = passenges.Where(m => m.TypeID == 1).ToList();
                var lstBabies = passenges.Where(m => m.TypeID == 3).ToList();
                int index = 0;
                for (index = 0; index < lstAduts.Count; index++)
                {
                    data5 += string.Format("&txtPax{17}_Gender={0}&txtPax{17}_LName={1}&txtPax{17}_FName={2}&txtPax{17}_Addr1={3}&txtPax{17}_City={4}&txtPax{17}_Ctry={5}&txtPax{17}_Prov={6}&txtPax{17}_EMail={7}&txtPax{17}_DOB_Day={8}&txtPax{17}_DOB_Month={9}&txtPax{17}_DOB_Year={10}&txtPax{17}_Phone2={11}&txtPax{17}_Phone1={11}&txtPax{17}_Passport={12}&dlstPax{17}_PassportExpiry_Day={13}&dlstPax{17}_PassportExpiry_Month={14}&lstPax{17}_PassportCtry={15}&txtPax{17}_Nationality={16}&hidPax{17}_Search=-1",
                 lstAduts[index].Sex,//0
                 HttpUtility.UrlEncode(lstAduts[index].FirstName),//1
                 HttpUtility.UrlEncode(lstAduts[index].Name),//2
                 HttpUtility.UrlEncode(lstAduts[index].Address),//3
                 HttpUtility.UrlEncode(lstAduts[index].City),//4
                 lstAduts[index].TK_CountryID,//5
                 lstAduts[index].TK_ProvineID,//6
                 HttpUtility.UrlEncode(strEmailDefault),//7
                 lstAduts[index].Birthday.Year > 1 ? lstAduts[index].Birthday.ToString("dd") : "",//8
                 lstAduts[index].Birthday.Year > 1 ? lstAduts[index].Birthday.ToString("MM") : "",//9
                 lstAduts[index].Birthday.Year > 1 ? lstAduts[index].Birthday.ToString("yyyy") : "",//10
                 new System.Text.RegularExpressions.Regex(@"\D")
            .Replace(lstAduts[index].Phone, string.Empty),//11
                 lstAduts[index].PassportNo,//12
                 lstAduts[index].PassportExp.Year > 1 ? lstAduts[index].PassportExp.ToString("dd") : "",//13
                 HttpUtility.UrlEncode(lstAduts[index].PassportExp.Year > 1 ? lstAduts[index].PassportExp.ToString("yyyy/MM") : ""),//14
                 lstAduts[index].PassportCountryID,//15
                 lstAduts[index].NationnalityID,//16
                 index + 1//17
                    );
                    if (lstBabies.Count > index)//nếu có em bé thì đi kèm theo người lớn
                    {
                        /*
                         * chkPax1_Infant:on
                            txtPax1_Infant_Name:Nho
                            txtPax1_Infant_DOB_Day:
                            txtPax1_Infant_DOB_Month:
                            txtPax1_Infant_DOB_Year:
                         * */
                        data5 += string.Format("&chkPax{0}_Infant=on&txtPax{0}_Infant_Name={1}&txtPax{0}_Infant_DOB_Day={2}&txtPax{0}_Infant_DOB_Month={3}&txtPax{0}_Infant_DOB_Year={4}",
                            index + 1,//0
                            lstBabies[index].FirstName + " " + lstBabies[index].Name,//1
                            lstBabies[index].Birthday.Year > 1 ? lstBabies[index].Birthday.ToString("dd") : "",//2
                            lstBabies[index].Birthday.Year > 1 ? lstBabies[index].Birthday.ToString("MM") : "",//3
                            lstBabies[index].Birthday.Year > 1 ? lstBabies[index].Birthday.ToString("yyyy") : ""//4
                            );
                    }
                }
                var lstChilds = passenges.Where(m => m.TypeID == 2).ToList();//điển thông tin trẻ em
                for (index = 0; index < lstChilds.Count; index++)
                {
                    data5 += string.Format("&txtPax{17}_Gender={0}&txtPax{17}_LName={1}&txtPax{17}_FName={2}&txtPax{17}_Addr1={3}&txtPax{17}_City={4}&txtPax{17}_Ctry={5}&txtPax{17}_Prov={6}&txtPax{17}_EMail={7}&txtPax{17}_DOB_Day={8}&txtPax{17}_DOB_Month={9}&txtPax{17}_DOB_Year={10}&txtPax{17}_Phone2={11}&txtPax{17}_Phone1={11}&txtPax{17}_Passport={12}&dlstPax{17}_PassportExpiry_Day={13}&dlstPax{17}_PassportExpiry_Month={14}&lstPax{17}_PassportCtry={15}&txtPax{17}_Nationality={16}&hidPax{17}_Search=-1",
                 "C",//0
                  HttpUtility.UrlEncode(lstChilds[index].FirstName),//1
                 HttpUtility.UrlEncode(lstChilds[index].Name),//2
                 HttpUtility.UrlEncode(lstChilds[index].Address),//3
                 HttpUtility.UrlEncode(lstChilds[index].City),//4
                 lstChilds[index].TK_CountryID,//5
                 lstChilds[index].TK_ProvineID,//6
                 HttpUtility.UrlEncode(strEmailDefault),//7
                 lstChilds[index].Birthday.Year > 1 ? lstChilds[index].Birthday.ToString("dd") : "",//8
                 lstChilds[index].Birthday.Year > 1 ? lstChilds[index].Birthday.ToString("MM") : "",//9
                 lstChilds[index].Birthday.Year > 1 ? lstChilds[index].Birthday.ToString("yyyy") : "",//10
                 new System.Text.RegularExpressions.Regex(@"\D")
            .Replace(lstChilds[index].Phone, string.Empty),//11
                 lstChilds[index].PassportNo,//12
                 lstChilds[index].PassportExp.Year > 1 ? lstChilds[index].PassportExp.ToString("dd") : "",//13
                 HttpUtility.UrlEncode(lstChilds[index].PassportExp.Year > 1 ? lstChilds[index].PassportExp.ToString("yyyy/MM") : ""),//14
                 lstChilds[index].PassportCountryID,//15
                 lstChilds[index].NationnalityID,//16
                 index + 1 + lstAduts.Count//17
                    );

                }

                respones = m_request.PostData(add5, data5);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add5] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                XuLy(html);

                #endregion

                #region 6.Chọn ghế & thức ăn

                string add6 = "https://ameliaweb3.intelisys.ca/VIETJET/AddOns.aspx?lang=vi&sesid=";
                string data6 = "__VIEWSTATE=" + viewstate + "&SesID=&DebugID=" + debugid + "&button=continue&m1th=2&m1p=1&m1p1=&m1p1rpg=&ctrSeatAssM=1&ctrSeatAssP=1";
                #region Get baggage info
                HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);
                var baggage = doc.DocumentNode.SelectNodes("//*/select[@class=\"lstShopSelect\"]");
                if (baggage != null)
                {
                    int indexBG = 0;
                    int indexPassenger = 0;
                    for (indexPassenger = 0; indexPassenger < baggage.Count; indexPassenger++)
                    {
                        var item = baggage[indexPassenger];
                        string strName = "";
                        string strValue = "";
                        string hidpaxitem = "";
                        string hidpaxitemValue = "";

                        #region BG depart
                        if (isBackReturnToDepart)
                        {
                            if (passenges[indexBG].BaggageReturnID > 0 && passenges[indexBG].BaggageReturnValue > 0)
                            {
                                strName = item.Attributes["name"].Value;
                                strName = HttpUtility.UrlEncode(strName);
                                string strBG = passenges[indexBG].BaggageReturnValue + "kgs";
                                //[contains(text(),'ABC')]
                                var lstSel = item.SelectNodes("option");
                                foreach (var opt in lstSel)
                                {
                                    if (opt.OuterHtml.IndexOf(strBG) > -1)
                                    {
                                        strValue = opt.Attributes["value"].Value;
                                        hidpaxitem = "hidPaxItem:" + opt.Attributes["hidpaxitem"].Value;
                                        hidpaxitem = HttpUtility.UrlEncode(hidpaxitem);
                                        hidpaxitemValue = opt.Attributes["hidpaxvalue"].Value;
                                        hidpaxitemValue = HttpUtility.UrlEncode(hidpaxitemValue);
                                        hidpaxitemValue = hidpaxitemValue.Replace("(", "%28").Replace(")", "%29");
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                strValue = "-1";
                            }
                            strValue = HttpUtility.UrlEncode(strValue);
                            data6 += string.Format("&{0}={1}", strName, strValue);
                            if (hidpaxitem.Length > 0)
                                data6 += string.Format("&{0}={1}", hidpaxitem, hidpaxitemValue);
                        }
                        else
                        {
                            hidpaxitemValue = "";
                            if (passenges[indexBG].BaggageDepartID > 0 && passenges[indexBG].BaggageDepartValue > 0)
                            {
                                strName = item.Attributes["name"].Value;
                                strName = HttpUtility.UrlEncode(strName);
                                string strBG = passenges[indexBG].BaggageDepartValue + "kgs";
                                //[contains(text(),'ABC')]
                                var lstSel = item.SelectNodes("option");
                                foreach (var opt in lstSel)
                                {
                                    if (opt.OuterHtml.IndexOf(strBG) > -1)
                                    {
                                        strValue = opt.Attributes["value"].Value;
                                        hidpaxitem = "hidPaxItem:" + opt.Attributes["hidpaxitem"].Value;
                                        hidpaxitem = HttpUtility.UrlEncode(hidpaxitem);
                                        hidpaxitemValue = opt.Attributes["hidpaxvalue"].Value;
                                        hidpaxitemValue = HttpUtility.UrlEncode(hidpaxitemValue);
                                        hidpaxitemValue = hidpaxitemValue.Replace("(", "%28").Replace(")", "%29");
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                strValue = "-1";
                            }
                            strValue = HttpUtility.UrlEncode(strValue);
                            data6 += string.Format("&{0}={1}", strName, strValue);
                            if (hidpaxitem.Length > 0)
                                data6 += string.Format("&{0}={1}", hidpaxitem, hidpaxitemValue);
                        }
                        #endregion

                        #region BG return
                        if (tkReturn != null)
                        {
                            indexPassenger++;
                            hidpaxitemValue = "";
                            if (passenges[indexBG].BaggageReturnID > 0 && passenges[indexBG].BaggageReturnValue > 0)
                            {
                                item = baggage[indexPassenger];
                                strName = item.Attributes["name"].Value;
                                strName = HttpUtility.UrlEncode(strName);
                                string strBG = passenges[indexBG].BaggageReturnValue + "kgs";
                                //[contains(text(),'ABC')]
                                var lstSel = item.SelectNodes("option");
                                foreach (var opt in lstSel)
                                {
                                    if (opt.OuterHtml.IndexOf(strBG) > -1)
                                    {
                                        strValue = opt.Attributes["value"].Value;
                                        hidpaxitem = "hidPaxItem:" + opt.Attributes["hidpaxitem"].Value;
                                        hidpaxitem = HttpUtility.UrlEncode(hidpaxitem);
                                        hidpaxitemValue = opt.Attributes["hidpaxvalue"].Value;
                                        hidpaxitemValue = HttpUtility.UrlEncode(hidpaxitemValue);
                                        hidpaxitemValue = hidpaxitemValue.Replace("(", "%28").Replace(")", "%29");
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                strValue = "-1";
                            }
                            strValue = HttpUtility.UrlEncode(strValue);
                            data6 += string.Format("&{0}={1}", strName, strValue);
                            if (hidpaxitem.Length > 0)
                                data6 += string.Format("&{0}={1}", hidpaxitem, hidpaxitemValue);
                        }
                        #endregion

                        indexBG++;
                        //indexPassenger++;
                    }
                }
                #endregion
                //return -1;
                respones = m_request.PostData(add6, data6);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add6] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                XuLy(html);

                #endregion

                #region 7.Thông tin thanh toán

                string add7 = "https://ameliaweb3.intelisys.ca/VIETJET/Payments.aspx?lang=vi&sesid=";
                string data7 = "__VIEWSTATE=" + viewstate + "&button=3rd&SesID=&DebugID=" + debugid + "&SesID=&DebugID=" + debugid + "&SesID=&DebugID=" + debugid + "&lstPmtType=5%2CPL%2C0%2CV%2C0%2C0%2C0&txtCardNo=&dlstExpiry=2014%2F01%2F31&txtCVC=&txtCardholder=&txtAddr1=&txtCity=&txtPCode=&lstCtry=-1&lstProv=-1&txtPhone=";
                respones = m_request.PostData(add7, data7);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add7] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                XuLy(html);

                #endregion

                #region 8.Xác nhận thanh toán

                string add8 = "https://ameliaweb3.intelisys.ca/VietJet/Confirm.aspx?lang=vi&sesid=";
                string data8 = "DebugID=" + debugid + "&SesID=&__VIEWSTATE=" + viewstate + "&button=continue&chkIAgree=on&txtPax1_FName=GIA%20TUYEN&txtPax1_Gender=M&txtPax1_LName=TRAN";
                respones = m_request.PostData(add8, data8);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add8] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                XuLy(html);

                #endregion

                #region 9.Kết thúc quá trình đặt chỗ & lấy thông tin

                string add9 = "https://ameliaweb3.intelisys.ca/VietJet/Processing.aspx?lang=vi&sesid=";
                string data9 = "__VIEWSTATE=" + viewstate + "&SesID=&DebugID=" + debugid;
                respones = m_request.PostData(add9, data9);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add9] = html;
                if (html.IndexOf("Hiện nay đang có quá nhiều khách hàng truy cập vào hệ thống đặt chỗ") > -1)
                {
                    LogManager.GetInstance().Warn("Vietjet: Busy");

                    return (int)BookingStatus.SERVERBUSY;
                }
                if (html.IndexOf("Rất tiếc không còn chỗ cho em bé. Hãy chọn ngày khác.") > -1)
                {
                    LogManager.GetInstance().Warn("Rất tiếc không còn chỗ cho em bé. Hãy chọn ngày khác.");

                    return (int)BookingStatus.NOTHAVEBABIESEAT;
                }
                GetResNumber(html);

                #endregion
                CacheManager.GetInstance().Delete(strKeyword);
                LogManager.GetInstance().Info("Vietjet: Booking OK");
                return (int)BookingStatus.BOOKED;
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Info("Vietjet booking error", ex);
                return (int)BookingStatus.UNKNOW;
            }
            finally
            {
                if (string.IsNullOrEmpty(GetCode()))
                {
                    this.SaveHTML(booking, lstResultHTML);
                }
            }
        }


        public decimal GetOutputFee(decimal TotalPrice, DateTime StartDate)
        {
            return 0;
        }

    }
}
